Imports System.ComponentModel

Public Class FileManagerView

    Friend WithEvents presenter As FileManagerViewPresenter

    Private Sub FileManagerView_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Me.presenter = New FileManagerViewPresenter(My.Forms.MainForm, Me)

    End Sub


    Private Sub FolderTreeView_NodeMouseClick(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles FolderTreeView.NodeMouseClick


        Me.presenter.BeginGetChildFolders(e.Node)
        Me.presenter.BeginGetFilesByFolder(Convert.ToInt32(e.Node.Tag))

        Me.FolderTreeView.SelectedNode = e.Node

    End Sub

    Private Sub FileListView_AfterLabelEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.LabelEditEventArgs) Handles FileListView.AfterLabelEdit

        Me.presenter.BeginAddFolder(e.Label)


    End Sub


    Private Sub FileListView_ColumnClick _
        (ByVal sender As Object, ByVal e As System.Windows.Forms.ColumnClickEventArgs) _
        Handles FileListView.ColumnClick


        Me.presenter.ReorderFileList(e)

    End Sub

    Private Sub FileListView_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles FileListView.MouseDown
        If e.Button = Windows.Forms.MouseButtons.Right Then

            Me.presenter.ShowFileContextMenu(e.Location)


        End If
    End Sub

    'Private Sub DeleteFileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteFileToolStripMenuItem.Click

    '    Me.presenter.BeginDeleteSelectedFiles()

    'End Sub

    'Private Sub FolderDeleteFilesToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles FolderDeleteFilesToolStripMenuItem.Click

    '    For Each item As ListViewItem In Me.FileListView.Items

    '        item.Selected = True

    '    Next

    '    Me.presenter.BeginDeleteSelectedFiles()

    'End Sub

    Private Sub AddFolderToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles AddFolderToolStripMenuItem.Click, FolderNewFolderToolStripMenuItem.Click


        Me.presenter.AddNewFolderItem()

    End Sub


    Friend Sub UploadFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
            Handles UploadFileToolStripMenuItem.Click, FolderUploadFilesToolStripMenuItem.Click

        If Not Me.UploadBackgroundWorker.IsBusy Then

            Dim uploadFileDialog As New OpenFileDialog
            uploadFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            uploadFileDialog.Filter = "All Files (*.*)|*.*"

            uploadFileDialog.CheckFileExists = True
            uploadFileDialog.CheckPathExists = True

            uploadFileDialog.Multiselect = True


            If uploadFileDialog.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then

                Me.UploadFiles(New List(Of String)(uploadFileDialog.FileNames))

            End If

        Else
            MessageBox.Show("Already uploading files, please wait for current files to complete and try again.", "Busy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

        End If

    End Sub


    Private Sub FolderDownloadFilesToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles FolderDownloadFilesToolStripMenuItem.Click
        For Each item As ListViewItem In Me.FileListView.Items

            item.Selected = True


        Next

        Me.DownloadFiles()

    End Sub

    Friend Sub DownloadFiles_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
        Handles SaveFileToolStripMenuItem.Click, FileListView.DoubleClick

        Me.DownloadFiles()

    End Sub

    Private Sub PropertiesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PropertiesToolStripMenuItem.Click

        Me.presenter.BeginGetInfo()


    End Sub

    Private Sub RefreshToolStripMenuItem_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles RefreshToolStripMenuItem.Click, FolderRefreshToolStripMenuItem.Click

        Me.presenter.RefreshFiles()

    End Sub


#Region "Background Workers"

 
    Private Sub DownloadBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles DownloadBackgroundWorker.DoWork

        Dim args As DownloadFileEventArgs = TryCast(e.Argument, DownloadFileEventArgs)

        If args IsNot Nothing Then

            e.Result = Me.presenter.DownloadFile(args.FileId, args.FileName)

        End If

    End Sub

    Private Sub DownloadBackgroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles DownloadBackgroundWorker.ProgressChanged

        Dim args As FileManagerEventArgs = TryCast(e.UserState, FileManagerEventArgs)

        If args IsNot Nothing Then

            Me.presenter.SetStatus(args.Status, args.HasError)

            Dim fileName As String = args.Status.Replace("File saved to ", "").Trim

            fileName = IO.Path.GetFileName(fileName)

            Me.DownloadsListBox.Items.Remove(fileName)

        End If

    End Sub

    Private Sub DownloadBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles DownloadBackgroundWorker.RunWorkerCompleted

        Dim args As DownloadFileEventArgs = TryCast(e.Result, DownloadFileEventArgs)

        If args IsNot Nothing Then

            Me.presenter.SetStatus(args.Status, args.HasError)

            Dim fileName As String = args.Status.Replace("File saved to ", "").Trim

            fileName = IO.Path.GetFileName(args.FileName)

            Me.DownloadsListBox.Items.Remove(fileName)

        End If

    End Sub

    Private Sub UploadBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles UploadBackgroundWorker.DoWork

        Dim args As Object() = TryCast(e.Argument, Object())

        If args IsNot Nothing Then

            Dim folderId As Integer = Convert.ToInt32(args(0))

            Dim file As String = args(1).ToString

            e.Result = Me.presenter.Uploadfile(folderId, file)

        End If

    End Sub

 
    Private Sub UploadBackgroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles UploadBackgroundWorker.ProgressChanged

        Dim args As FileTransferEventArgs = TryCast(e.UserState, FileTransferEventArgs)

        Me.presenter.SetStatus(args.Status, args.HasError)

    End Sub


    Private Sub UploadBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles UploadBackgroundWorker.RunWorkerCompleted


        Dim args As FileTransferEventArgs = TryCast(e.Result, FileTransferEventArgs)

        Me.UploadsListBox.Items.Remove(IO.Path.GetFileName(args.FileName))

        If Not args.HasError Then

            Me.presenter.RefreshFiles()

        End If

        Me.presenter.SetStatus(args.Status, args.HasError)

    End Sub


#End Region

#Region "Drag and Drop"

    Private Sub FileListView_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles FileListView.DragDrop

        Try
            If e.Data.GetDataPresent(DataFormats.FileDrop) Then

                Dim files As String() = TryCast(e.Data.GetData(DataFormats.FileDrop), String())

                If files IsNot Nothing Then

                    Dim existingFiles As New List(Of String)

                    For Each file As String In files

                        If IO.File.Exists(file) Then

                            existingFiles.Add(file)

                        End If
                    Next

                    Me.UploadFiles(existingFiles)

                End If

            End If


        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

    End Sub

    Private Sub FileListView_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles FileListView.DragEnter
        If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then
            e.Effect = DragDropEffects.All
        End If
    End Sub


#End Region


    Private Sub UploadFiles(ByVal fileNames As List(Of String))

        Dim folderId As Integer = -1

        If Me.FolderTreeView.SelectedNode IsNot Nothing Then

            folderId = Convert.ToInt32(Me.FolderTreeView.SelectedNode.Tag)

        End If

        For Each file As String In fileNames

            Me.UploadsListBox.Items.Add(IO.Path.GetFileName(file))

            Dim worker As New System.ComponentModel.BackgroundWorker()

            AddHandler worker.DoWork, AddressOf UploadBackgroundWorker_DoWork

            AddHandler worker.RunWorkerCompleted, AddressOf UploadBackgroundWorker_RunWorkerCompleted

            worker.RunWorkerAsync(New Object() {folderId, file})

        Next




        'Me.UploadBackgroundWorker.RunWorkerAsync(New Object() {folderId, fileNames})

    End Sub

    Private Sub DownloadFiles()
        If Not Me.DownloadBackgroundWorker.IsBusy Then

            My.Forms.MainForm.DownloadFolderBrowserDialog.SelectedPath = Me.presenter.GetDownloadFolder

            If My.Forms.MainForm.DownloadFolderBrowserDialog.ShowDialog = DialogResult.OK Then

                Dim downloadPath As String = My.Forms.MainForm.DownloadFolderBrowserDialog.SelectedPath

                If String.IsNullOrEmpty(downloadPath) Then

                    downloadPath = Me.presenter.GetDownloadFolder

                End If


                Dim fileList As New Generic.Dictionary(Of Integer, String)

                Dim files As ListView.SelectedListViewItemCollection = Me.FileListView.SelectedItems


                For Each item As ListViewItem In files

                    'fileList.Add(CInt(item.Tag), IO.Path.Combine(downloadPath, item.Text))

                    
                    Me.DownloadsListBox.Items.Add(item.Text)

                    Dim worker As New backgroundworker

                    AddHandler worker.DoWork, AddressOf DownloadBackgroundWorker_DoWork

                    AddHandler worker.RunWorkerCompleted, AddressOf DownloadBackgroundWorker_RunWorkerCompleted

                    Dim args As New DownloadFileEventArgs _
                        (Nothing, Integer.Parse(item.Tag.ToString), _
                         IO.Path.Combine(downloadPath, item.Text))

                    worker.RunWorkerAsync(args)

                Next


                ' Me.DownloadBackgroundWorker.RunWorkerAsync(fileList)

            End If

        Else

            MessageBox.Show("Already downloading, please wait for current files to complete and try again.", "Busy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

        End If
    End Sub


End Class
